/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.martinkrasa.golftourweb.site;

import com.martinkrasa.golftourweb.site.entity.TournamentResult;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;

@Repository
public class InMemoryTournamentResultRepository implements TournamentResultRepository {

    private volatile long tournamentResultIdSequence = 1L;
    private final Map<Long, TournamentResult> tournamentResultList = new LinkedHashMap<>();
    
    @Override
    public List<TournamentResult> getTournamentResults(long id) {
        
        List<TournamentResult> tournamentResults = new ArrayList<>(this.tournamentResultList.values());
        tournamentResults.removeIf(r -> r.getTournamentId() != id);
        return tournamentResults;
    }

    @Override
    public void addTournamentResults(long tournamentId, List<TournamentResult> tournamentResultsToAdd) {
        
        for (TournamentResult result : tournamentResultsToAdd) {
            long id = this.getNextTournamentResultId();
            result.setId(id);
            result.setTournamentId(tournamentId);
            this.tournamentResultList.put(id, result);
        }
    }
    
    private synchronized long getNextTournamentResultId() {
        return this.tournamentResultIdSequence++;
    }
}
